#include "ipc/ipc_main.h"

static main_process_message_handeler_t ipc_main_handeler_t;

void _set_main_process_message_handeler(on_main_process_message_handler on_handler) {
    ipc_main_handeler_t.handler = on_handler;
}

// 发送消息给渲染进程
// request_id  是否返回， 0 不返回， 1 返回
void _ipc_main_send(cef_browser_t *browser, const char *event_name, IPC_Value *value,
                   int request_id) {
    // 构造进程消息
    cef_string_t message_name = {};
    cef_string_utf8_to_utf16("main-call", strlen("main-call"), &message_name);

    cef_process_message_t *proc_msg = cef_process_message_create(&message_name);
    cef_list_value_t *msg_args = proc_msg->get_argument_list(proc_msg);
    msg_args->set_size(msg_args, 3);

    cef_string_t event_name_str = {};
    cef_string_utf8_to_utf16(event_name, strlen(event_name), &event_name_str);
    msg_args->set_string(msg_args, 0, &event_name_str);

    if (value != NULL) {
        cef_value_t *value_cef = ipc_value_to_cef_value(value);
        msg_args->set_value(msg_args, 1, value_cef);
    }

    msg_args->set_int(msg_args, 2, request_id);

    // 发送消息到渲染进程
    cef_frame_t *main_frame = browser->get_main_frame(browser);

    // 清理
    main_frame->send_process_message(main_frame, PID_RENDERER, proc_msg);

    cef_string_clear(&message_name);
    cef_string_clear(&event_name_str);
    ipc_value_free(value);
}

// 主进程处理来自JS的消息
int on_main_process_message_received(cef_browser_t *browser, struct _cef_frame_t *frame, cef_process_id_t source_pid,
                                     cef_process_message_t *message) {
    // format_output_log("info", __FILE__, __LINE__, __FUNCTION__, "renderer-main");
    cef_string_userfree_t message_name = message->get_name(message);
    cef_string_utf16_t call = {};
    cef_string_utf8_to_utf16("renderer-call", strlen("renderer-call"), &call);
    cef_string_utf16_t callback = {};
    cef_string_utf8_to_utf16("renderer-response", strlen("renderer-response"), &callback);

    int ret_value = 0;

    // js 调用
    cef_list_value_t *args = message->get_argument_list(message);
    // 解析事件名、参数、请求ID
    cef_string_userfree_t event_name = args->get_string(args, 0);
    cef_value_t * request_data_cef = args->get_value(args, 1);
    IPC_Value *request_data = ipc_value_create_by_cef_value(request_data_cef);

    // 查找时转换CEF字符串为C字符串
    cef_string_utf8_t event_name_utf8 = {};
    cef_string_utf16_to_utf8(event_name->str, event_name->length, &event_name_utf8);

    LOG_INFO("renderer-main event_name=%s", event_name_utf8.str);

    if (cef_string_utf16_cmp(message_name, &call) == 0) {
        int request_id = args->get_int(args, 2);
        LOG_INFO("renderer-call request_id: %d", request_id);
        // // 查找事件处理器
        // IPC_Main_Handler handler = (IPC_Main_Handler)hashmap_get(ipcMain_handler_map, event_name_utf8.str);

        // format_output_log("info", __FILE__, __LINE__, __FUNCTION__, "renderer-call get handler end ");

        if (ipc_main_handeler_t.handler) {
            if (request_id == 0) {
                LOG_INFO("renderer-call handler exec no return ");
                ipc_main_handeler_t.handler(event_name_utf8.str, 0, request_data);
                // format_output_log("info", __FILE__, __LINE__, __FUNCTION__, "renderer-call handler exec no return end");
            } else if (request_id == 1) {
                // format_output_log("info", __FILE__, __LINE__, __FUNCTION__, "renderer-call handler exec return ");
                cef_string_t main_response_str = {};
                cef_string_utf8_to_utf16("main-response", strlen("main-response"), &main_response_str);
                format_output_log("info", __FILE__, __LINE__, __FUNCTION__, "renderer-call handler response message name %ls", main_response_str.str);
                cef_process_message_t *response_msg = cef_process_message_create(&main_response_str);
                cef_list_value_t *msg_args = response_msg->get_argument_list(response_msg);
                msg_args->set_size(msg_args, 2);
                msg_args->set_string(msg_args, 0, event_name);

                IPC_Value *response_data = ipc_main_handeler_t.handler(event_name_utf8.str, 1, request_data);
               
                cef_value_t *response_value = ipc_value_to_cef_value(response_data);
                if (!response_value || !response_value->is_valid(response_value)) {
                    LOG_ERROR("Invalid response_data");
                    return 0;
                }
                msg_args->set_value(msg_args, 1, response_value);
        
                if (!cef_currently_on(TID_UI)) {
                    LOG_ERROR("renderer-call handler exec TID_UI");
                }

                if (!frame->is_valid(frame)) {
                    LOG_ERROR("renderer-call handler exec frame->is_valid(frame) ");
                }
                // 发送返回消息到渲染进程
                frame->send_process_message(frame, PID_RENDERER, response_msg);

                if (response_data) {
                    ipc_value_free(response_data);
                }
                cef_string_clear(&main_response_str);
            }
            ret_value = 1;
        }
    } else if (cef_string_utf16_cmp(message_name, &callback) == 0) {
        LOG_DEBUG("renderer-response");
        // 查找回调函数
        ipc_main_handeler_t.handler(event_name_utf8.str, 2, request_data);
        ret_value = 1;
    }

    // 清理
    cef_string_clear(&call);
    cef_string_clear(&callback);
    cef_string_utf8_clear(&event_name_utf8);
    cef_string_userfree_free(event_name);
    ipc_value_free(request_data);
    request_data_cef->base.release((cef_base_ref_counted_t *)request_data_cef);
    message->base.release((cef_base_ref_counted_t *)message);
    LOG_DEBUG("renderer-main end return value %d", ret_value);
    return ret_value;
}
